/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include <isa.h>
#include <cpu/cpu.h>
#include <common.h>
#include <memory/vaddr.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "sdb.h"

static int is_batch_mode = false;

void init_regex();
void init_wp_pool();

/* We use the `readline' library to provide more flexibility to read from stdin. */
static char* rl_gets() {
  static char *line_read = NULL;

  if (line_read) {
    free(line_read);
    line_read = NULL;
  }

  line_read = readline("(nemu) ");

  if (line_read && *line_read) {
    add_history(line_read);
  }

  return line_read;
}

static int cmd_c(char *args) {
  cpu_exec(-1);
  return 0;
}


static int cmd_q(char *args) {
  return -1;
}

static int cmd_help(char *args);

static int cmd_si(char *args);

static int cmd_info(char *args);

static int cmd_x(char *args);

static int cmd_p(char *args);

static int cmd_w(char *args);

static int cmd_d(char* args);

static struct {
  const char *name;
  const char *description;
  int (*handler) (char *);
} cmd_table [] = {
  { "help", "Display information about all supported commands", cmd_help },
  { "c", "Continue the execution of the program", cmd_c },
  { "q", "Exit NEMU", cmd_q },
  { "si", "Let the program pause after executing N instructions in one step,When N is not given, the default is 1", cmd_si},
  { "info", "Print program status of SUBCMD", cmd_info},
  { "x", "Find the value of the expression EXPR and use the result as the starting memory Address, output N consecutive 4 bytes in hexadecimal format ", cmd_x},
  { "p", "Find the value of the expression EXPR", cmd_p},
  { "w", "Pause program execution when the value of the expression EXPR changes", cmd_w},
  { "d", "Delete Watchpoint", cmd_d}
  /* TODO: Add more commands */

};


#define NR_CMD ARRLEN(cmd_table)

static int cmd_help(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");
  int i;

  if (arg == NULL) {
    /* no argument given */
    for (i = 0; i < NR_CMD; i ++) {
      printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
    }
  }
  else {
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(arg, cmd_table[i].name) == 0) {
        printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
        return 0;
      }
    }
    printf("Unknown command '%s'\n", arg);
  }
  return 0;
}

static int cmd_si(char *args){
  char *arg = strtok(args, " ");

  if (arg == NULL){
    /* default n is 1*/
    cpu_exec(1);
  }
  else {
    int n;
    sscanf(args, "%d", &n);
    if (n < -1){
      printf("Error, N should greater than or equal to -1\n");
    }
    else {
      cpu_exec(n);
    }
  }
  return 0;
}

static int cmd_info(char *args){
  char *arg = strtok(args, " ");
  if (strcmp(arg, "r") == 0) {
    isa_reg_display();
  }
  else if(strcmp(arg, "w") == 0){
    WP* node = get_head();
    if(node == NULL){
      Log("Don't exit any watchpoints");
      return 0;
    }
    printf("Num\tExpression\tLast value\n");
    while(node != NULL){
      printf("%d\t%s\t%lu\n",node->NO, node->expression, node->last_value);
      node = node->next;
    }
  }
  else {
    printf("unknow status");
  }
  return 0;
}

static int cmd_x(char *args) {
  char *N = strtok(NULL, " ");
  char *EXPR = strtok(NULL, "");
  printf("EXPR: %s\n", EXPR);
  int len;
  vaddr_t address;

  sscanf(N, "%d", &len);
  bool success;
  address = expr(EXPR, &success);

  printf("address: 0x%016lx\n", address);
  int i;
  for(i = 0; i < len; i++){
    printf("%lu ", vaddr_read(address, 4));
    address += 4;
  }
  puts("");
  return 0;
}

static int cmd_p(char *args){
  char* EXPR = strtok(args, "");
  bool success;
  word_t result = expr(EXPR, &success);
  if(!success){
    printf("error when calculate the express: %s", EXPR);
    assert(0);
  }
  printf("%s = %lu\n", args, result);
  return 0;
}

static int cmd_w(char *args){
  char* EXPR = strtok(args, "");
  WP* node = new_wp();
  node->expression = (char*)malloc(sizeof(EXPR) + 5);
  strcpy(node->expression, EXPR);
  bool success;
  word_t result = expr(EXPR, &success);
  (*node).last_value = result;
  printf("NO %d watchpoint, expression: %s, last value: %lu\n", (*node).NO, (*node).expression, (*node).last_value);
  return 0;
}

static int cmd_d(char *args){
  char* N = strtok(args, " ");
  int n;
  sscanf(N, "%d", &n);
  free_wp_by_NO(n);
  printf("NO. %d watchpoint has been deleted\n", n);
  return 0;
}

void sdb_set_batch_mode() {
  is_batch_mode = true;
}

void sdb_mainloop() {
  if (is_batch_mode) {
    cmd_c(NULL);
    return;
  }

  for (char *str; (str = rl_gets()) != NULL; ) {
    char *str_end = str + strlen(str);

    /* extract the first token as the command */
    char *cmd = strtok(str, " ");
    if (cmd == NULL) { continue; }

    /* treat the remaining string as the arguments,
     * which may need further parsing
     */
    char *args = cmd + strlen(cmd) + 1;
    if (args >= str_end) {
      args = NULL;
    }

#ifdef CONFIG_DEVICE
    extern void sdl_clear_event_queue();
    sdl_clear_event_queue();
#endif

    int i;
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(cmd, cmd_table[i].name) == 0) {
        if (cmd_table[i].handler(args) < 0) { return; }
        break;
      }
    }

    if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }
  }
}

void init_sdb() {
  /* Compile the regular expressions. */
  init_regex();

  /* Initialize the watchpoint pool. */
  init_wp_pool();
}
